package controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sql.RegisterBookInDb;
import bean.BookBean;
import bean.CustomerBean;

public class RegisterBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public RegisterBook() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);				
		String address = "";
		
		// get session customer bean for id 
		CustomerBean customer = (CustomerBean) session.getAttribute("customer");
		if (customer == null) {		// customer is not logged in
			address = "../login.jsp";
			response.sendRedirect(address);		
		}
		
		// get form parameters and store in BookBean
		BookBean bookBean = new BookBean();
		bookBean.setIsbn(request.getParameter("isbn"));
		bookBean.setTitle(request.getParameter("title"));
		bookBean.setAuthorFirstName(request.getParameter("authorFirstName"));
		bookBean.setAuthorLastName(request.getParameter("authorLastName"));
		bookBean.setPublisher(request.getParameter("publisher"));
		bookBean.setCopyright(Integer.parseInt(request.getParameter("copyright")));
		bookBean.setNumOfPages(Integer.parseInt(request.getParameter("numberOfPages")));
		bookBean.setEdition(request.getParameter("edition"));
		bookBean.setDescription(request.getParameter("description"));
		bookBean.setPrice(Double.parseDouble(request.getParameter("price")));
		bookBean.setBookConditionCode(request.getParameter("conditionCode"));
		bookBean.setBookCategoryCode(request.getParameter("categoryCode"));
		
		bookBean.setBookId(0);	// not used
		bookBean.setIsSold("N");
		bookBean.setSellerId(customer.getCustomerId());
		
		// insert record in to database
		RegisterBookInDb registerBookInDb = new RegisterBookInDb(bookBean);
		try {
			registerBookInDb.save();
			address = "/WEB-INF/bookRegistered.jsp";
			RequestDispatcher dispatcher = request.getRequestDispatcher(address);
			dispatcher.forward(request, response);
		} catch (SQLException e) {e.printStackTrace();
		} catch (ClassNotFoundException e) {e.printStackTrace();
		}
	}
}
